package itsm.isperp.module.service.bpm;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.service.BaseService;
import itsm.isperp.module.entity.bpm.BpmNodeSetting;
import itsm.isperp.module.entity.db.DbEntity;
import itsm.isperp.module.repository.bpm.BpmNodeSettingMapper;
import itsm.isperp.workflow.graph.Node;
import itsm.isperp.workflow.service.BpmProcessDefinitaionService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

/**
 * 
 * 流程节点设置服务
 * 
 * 
 * @author lizx
 * @date 2013-7-3
 * 
 */
@Service
public class BpmNodeSettingService extends BaseService<BpmNodeSetting> {

	@Autowired
	BpmNodeSettingMapper bpmNodeSettingMapper;

	@Override
	public BpmNodeSettingMapper getRepository() {
		return bpmNodeSettingMapper;
	}

	public BpmNodeSetting findByNodeId(String actNodeId) {
		return this.getRepository().findByNodeId(actNodeId);
	}

	public Map<String, Object> findMapByNodeId(String actNodeId,
			String... selectColumns) {
		return this.getRepository().findMapByNodeId(actNodeId, selectColumns);
	}

	public DbEntity findDbEntityById(String id) {
		return bpmNodeSettingMapper.findDbEntityById(id);
	}
	
	public String getProcessKeyByNodeId(String nodeId)
	{
		JdbcTemplate jdbcTemplate = ContextHolder
				.getSpringBean("jdbcTemplate");
		String sql="SELECT act_re_procdef_key FROM bpm_process_setting WHERE id=(SELECT bpm_process_setting_id FROM bpm_node_setting WHERE id='"+nodeId+"')";
		List<Map<String,Object>> list1=jdbcTemplate.queryForList(sql);
		if(list1.size()>0)
			return list1.get(0).get("act_re_procdef_key").toString();
		else
			return null;
	}
	
	public List<Node> getAllNodes(String processKey) {
		BpmProcessDefinitaionService bpmProcessDefinitaionService = ContextHolder
				.getSpringBean("bpmProcessDefinitaionService");
		if(StringUtils.isEmpty(processKey))
			return null;
		List<ActivityImpl> activities= bpmProcessDefinitaionService.getProcessDefinitionEntityByKey(processKey).getActivities();
		List<Node> nodes = new ArrayList<>();
		for(ActivityImpl act:activities)
		{
			Map<String, Object> m = act.getProperties();
			if ("userTask".equals(m.get("type").toString())) {
				Node n = new Node();
				n.setId(act.getId());
				n.setName(m.get("name").toString());
				nodes.add(n);
			}
		}
		
		return nodes; 

	}

}
